package com.awei.project.service.impl;

import java.util.*;

import com.awei.project.cos.COSoperate;
import com.awei.project.model.dto.userRequest.UserQueryRequest;
import com.awei.project.model.dto.userRequest.UserRegisterRequest;
import com.awei.project.model.enums.UserRoleEnum;
import com.awei.project.model.vo.UserVO;
import com.awei.project.utils.AlgorithmUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.awei.project.common.ErrorCode;
import com.awei.project.exception.BusinessException;
import com.awei.project.mapper.UserMapper;
import com.awei.project.model.entity.User;
import com.awei.project.service.UserService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.awei.project.constant.UserConstant.SALT;
import static com.awei.project.constant.UserConstant.USER_LOGIN_STATE;


/**
 * 用户服务实现类
 *
 * @author 小维哥
 * @version 1.2
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
        @Resource
        private RedisTemplate<String, Object> redisTemplate;

        @Resource
        private UserMapper userMapper;
        @Resource
       private COSoperate coSoperate;

        @Override
        public long userRegister(UserRegisterRequest userRegisterRequest) {
                // 1. 校验
                String checkPassword = userRegisterRequest.getCheckPassword();
                String userPassword = userRegisterRequest.getUserPassword();
                String userAccount = userRegisterRequest.getUserAccount();
                if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
                }
                if (userAccount.length() < 4) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
                }
                if (userPassword.length() < 8 || checkPassword.length() < 8) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
                }
                //校验性别，邮箱和电话就不太严格了
                Integer gender = userRegisterRequest.getGender();
                if (gender == null || gender < 0 || gender > 2) {
                        throw new BusinessException(ErrorCode.OPERATION_ERROR, "性别参数错误");
                }
                String phone = userRegisterRequest.getPhone();
                if (phone.length() > 20 || phone.isEmpty()) {
                        throw new BusinessException(ErrorCode.OPERATION_ERROR, "哥，电话别编的太夸张");
                }
                String email = userRegisterRequest.getEmail();
                if (email.length() > 20 || email.isEmpty()) {
                        throw new BusinessException(ErrorCode.OPERATION_ERROR, "哥，邮箱别编的太夸张");
                }
                // 密码和校验密码相同
                if (!userPassword.equals(checkPassword)) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
                }
                synchronized (userAccount.intern()) {
                        // 账户不能重复
                        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("userAccount", userAccount);
                        long count = userMapper.selectCount(queryWrapper);
                        if (count > 0) {
                                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
                        }
                        // 2. 加密
                        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
                        // 3. 插入数据
                        User user = new User();
                        user.setUserAccount(userAccount);
                        user.setUserPassword(encryptPassword);
                        user.setEmail(email);
                        user.setGender(gender);
                        user.setPhone(phone);
                        boolean saveResult = this.save(user);
                        if (!saveResult) {
                                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
                        }
                        return user.getId();
                }
        }

        @Override
        public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
                // 1. 校验
                if (StringUtils.isAnyBlank(userAccount, userPassword)) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
                }
                if (userAccount.length() < 4) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
                }
                if (userPassword.length() < 8) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
                }
                // 2. 加密
                String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
                // 查询用户是否存在
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("userAccount", userAccount);
                queryWrapper.eq("userPassword", encryptPassword);
                User user = userMapper.selectOne(queryWrapper);
                // 用户不存在
                if (user == null) {
                        log.info("user login failed, userAccount cannot match userPassword");
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
                }
                // 3. 记录用户的登录态
                User safetyUser = getSafetyUser(user);
                request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
                return safetyUser;
        }

        /**
         * 获取当前登录用户
         */
        @Override
        public User getLoginUser(HttpServletRequest request) {
                // 先判断是否已登录
                Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
                User currentUser = (User) userObj;
                if (currentUser == null || currentUser.getId() == null) {
                        throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
                }
                long userId = currentUser.getId();
                currentUser = this.getById(userId);
                if (currentUser == null) {
                        throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
                }
                return currentUser;
        }

        /**
         * 是否为管理员
         */
        @Override
        public boolean isAdmin(HttpServletRequest request) {
                // 仅管理员可查询
                Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
                User user = (User) userObj;
                return user != null && UserRoleEnum.ADMIN_ROLE.getValue() == user.getUserRole();
        }

        @Override
        public boolean isAdmin(User user) {
                // 仅管理员可查询
                return user != null && UserRoleEnum.ADMIN_ROLE.getValue() == user.getUserRole();
        }

        @Override
        public Integer updateUserById(User user, User loginUser) {
                long userId = loginUser.getId();
                if (userId <= 0) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                // 如果是管理员，允许更新任意用户
                // 如果不是管理员，只允许更新当前（自己的）信息  不知道为啥，出现状态码不一致
                if (!isAdmin(loginUser) && userId != loginUser.getId()) {
                        throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
                }
                User oldUser = userMapper.selectById(userId);
                if (oldUser == null) {
                        throw new BusinessException(ErrorCode.NULL_ERROR);
                }
                //如果用户没有传任何要更新的值，就直接报错，不用执行 update 语句
                if (!judgeUpdateUser(user)) {
                        throw new BusinessException(ErrorCode.NULL_ERROR);
                }
                return userMapper.updateById(user);
        }

        /**
         * 判断用户除了id外是否都为空
         * @param user
         * @return
         */
        private boolean judgeUpdateUser(User user) {
                String username = user.getUsername();
                String userAccount = user.getUserAccount();
                String avatarUrl = user.getAvatarUrl();
                Integer gender = user.getGender();
                String userPassword = user.getUserPassword();
                String phone = user.getPhone();
                String email = user.getEmail();
                Integer userStatus = user.getUserStatus();
                String profile = user.getProfile();
                String tags = user.getTags();
                return isEmpty(username) || isEmpty(userAccount) || isEmpty(avatarUrl) || isEmpty(gender) || isEmpty(userPassword) ||
                        isEmpty(phone) || isEmpty(email) || isEmpty(userStatus) || isEmpty(tags)|| isEmpty(profile);
        }

        /**
         * 判断obj对象和string是否为空
         * @param obj
         * @return
         */
        private boolean isEmpty(Object obj) {
                if (obj == null) {
                        return false;
                }
                if (obj instanceof String) {
                        return !((String) obj).isEmpty();
                }
                return true;
        }

        /**
         * 用户注销
         */
        @Override
        public boolean userLogout(HttpServletRequest request) {
                if (request.getSession().getAttribute(USER_LOGIN_STATE) == null) {
                        throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
                }
                // 移除登录态
                request.getSession().removeAttribute(USER_LOGIN_STATE);
                return true;
        }

        @Override
        public User getSafetyUser(User originUser) {
                if (originUser == null) {
                        return null;
                }
                User safetyUser = new User();
                safetyUser.setId(originUser.getId());
                safetyUser.setUsername(originUser.getUsername());
                safetyUser.setUserAccount(originUser.getUserAccount());
                safetyUser.setAvatarUrl(originUser.getAvatarUrl());
                safetyUser.setGender(originUser.getGender());
                safetyUser.setPhone(originUser.getPhone());
                safetyUser.setEmail(originUser.getEmail());
                safetyUser.setPlanetCode(originUser.getPlanetCode());
                safetyUser.setUserRole(originUser.getUserRole());
                safetyUser.setUserStatus(originUser.getUserStatus());
                safetyUser.setCreateTime(originUser.getCreateTime());
                safetyUser.setTags(originUser.getTags());
                return safetyUser;
        }

        @Override
        public UserVO getUserVo(User originUser) {
                if (originUser == null) {
                        return null;
                }
                UserVO safetyUser = new UserVO();
                safetyUser.setId(originUser.getId());
                safetyUser.setUsername(originUser.getUsername());
                safetyUser.setUserAccount(originUser.getUserAccount());
                safetyUser.setAvatarUrl(originUser.getAvatarUrl());
                safetyUser.setGender(originUser.getGender());
                Integer userRole = originUser.getUserRole();
                UserRoleEnum values = UserRoleEnum.getValues(userRole);
                safetyUser.setUserRole(values.getText());
                safetyUser.setTags(originUser.getTags());
                safetyUser.setCreateTime(originUser.getCreateTime());
                safetyUser.setUpdateTime(originUser.getUpdateTime());
                return safetyUser;
        }

        @Override
        public Page<UserVO> listUserByPage(UserQueryRequest userQueryRequest, long size, long current) {
                User userQuery = new User();
                if (userQueryRequest != null) {
                        BeanUtils.copyProperties(userQueryRequest, userQuery);
                        current = userQueryRequest.getCurrent();
                        size = userQueryRequest.getPageSize();
                }//此接口经常掉用，优化方案：使用redis进行缓存
                String redisKey = String.format("awei:user:listpage:%s", userQuery.getId());
                ValueOperations<String, Object> redString = redisTemplate.opsForValue();
                Page<User> userPage = (Page<User>) redString.get(redisKey);
                Page<User> page = new LambdaQueryChainWrapper<>(this.getBaseMapper()).select(User::getGender).page(userPage);
                //缓存没有再进行数据库查询
                if (userPage == null) {
                        QueryWrapper<User> queryWrapper = new QueryWrapper<>(userQuery);
                        userPage = this.page(new Page<>(current, size), queryWrapper);
                        try {
                                redString.set(redisKey, userPage, 60000, TimeUnit.MILLISECONDS);
                        } catch (Exception e) {
                                log.error("redis 数据插入错误", e);
                        }
                }
                return getSafePageUser(page);
        }

        /**
         * @param userPage:分页功能的user数据
         * @return 分页功能数据的脱敏
         */
        @Override
        public Page<UserVO> getSafePageUser(Page<User> userPage) {
                Page<UserVO> userVOPage = new PageDTO<>(userPage.getCurrent(), userPage.getSize(), userPage.getTotal());
                List<UserVO> userVOList = userPage.getRecords().stream().map(user -> {
                        UserVO userVO = new UserVO();
                        BeanUtils.copyProperties(user, userVO);
                        return userVO;
                }).collect(Collectors.toList());
                return userVOPage.setRecords(userVOList);
        }

        @Override
        public List<User> matchUsers(long num, User loginUser) {
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                queryWrapper.select("id", "tags");
                queryWrapper.isNotNull("tags");
                List<User> userList = this.list(queryWrapper);
                String tags = loginUser.getTags();
                Gson gson = new Gson();
                List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>() {
                }.getType());
                // 用户列表的下标 => 相似度
                List<Pair<User, Long>> list = new ArrayList<>();
                // 依次计算所有用户和当前用户的相似度
                for (int i = 0; i < userList.size(); i++) {
                        User user = userList.get(i);
                        String userTags = user.getTags();
                        // 无标签或者为当前用户自己
                        if (StringUtils.isBlank(userTags) || user.getId() == loginUser.getId()) {
                                continue;
                        }
                        List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>() {
                        }.getType());
                        // 计算分数
                        long distance = AlgorithmUtils.minDistance(tagList, userTagList);
                        MutablePair<Object, Object> aaa = new MutablePair<>();
                        list.add(new MutablePair<>(user, distance));
                }
                // 按编辑距离由小到大排序
                List<Pair<User, Long>> topUserPairList = list.stream()
                        .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
                        .limit(num)
                        .collect(Collectors.toList());
                // 原本顺序的 userId 列表
                List<Long> userIdList = topUserPairList.stream().map(pair -> pair.getKey().getId()).collect(Collectors.toList());
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.in("id", userIdList);
                // 1, 3, 2
                // User1、User2、User3
                // 1 => User1, 2 => User2, 3 => User3
                Map<Long, List<User>> userIdUserListMap = this.list(userQueryWrapper)
                        .stream()
                        .map(this::getSafetyUser)
                        .collect(Collectors.groupingBy(User::getId));
                List<User> finalUserList = new ArrayList<>();
                for (Long userId : userIdList) {
                        finalUserList.add(userIdUserListMap.get(userId).get(0));
                }
                return finalUserList;
        }

        @Override
        public int updateTags(Long userId, User loginUser, List<String> tags) {
                //更新用户信息，先获取到用户的 id，判断 id < 0 就没有此用户
                if (userId < 0) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                //将拿到的标签列表转换成 Json格式
                Gson gson = new Gson();
                int gender = -1;
                for (String str : tags) {
                        if (str.equals("男")) {
                                tags.remove("男");
                                gender = 0;
                                break;
                        } else if (str.equals("女")) {
                                tags.remove("女");
                                gender = 1;
                                break;
                        }
                }
                String StrToJson = gson.toJson(tags);
                //拿到要修改的用户id，然后修改
                //当前用户态的用户（已登录）不是管理员，并且修改的用户信息也不是已登录用户的（修改的不是自己的），就抛异常
                if (!isAdmin(loginUser) && !Objects.equals(userId, loginUser.getId())) {
                        throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
                }
                User user = new User();
                user.setId(userId);
                if (gender >= 0) {
                        user.setGender(gender);
                }
                user.setTags(StrToJson);
                //触发更新
                return this.baseMapper.updateById(user);
        }

        @Override
        public boolean updateUserImg(MultipartFile file, User loginUser) {
                if(loginUser==null||file==null){
                        throw new BusinessException(ErrorCode.NULL_ERROR);
                }
                Date updateTime = loginUser.getUpdateTime();
                Calendar cal = Calendar.getInstance();
                // 限制修改头像的时间频率：3分钟间隔
                cal.setTime(new Date());
                cal.add(Calendar.MINUTE, -3);
                Date updatedTime = cal.getTime();
                if(!updateTime.before(updatedTime)){
                        throw new BusinessException(ErrorCode.OPERATION_ERROR,"3分钟内仅能修改一次头像");
                }
                String upload = coSoperate.upload(file);
                if(upload.isEmpty()){
                        throw new BusinessException(ErrorCode.OPERATION_ERROR,"文件路径为空");
                }
                loginUser.setAvatarUrl(upload);
                boolean b = this.updateById(loginUser);
                if(!b){
                        throw new BusinessException(ErrorCode.OPERATION_ERROR,"修改头像失败");
                }
                return true;
        }

        @Override
        public List<User> searcherUserByTags(List<String> tagNameList, int size, int current) {
                if (CollectionUtils.isEmpty(tagNameList)) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                // 拼接 and 查询
                // like '辅助 and like '中路'
                for (String tagName : tagNameList) {
                        if (tagName.equals("女")) {
                                queryWrapper.or().like("gender", 1);
                        } else if (tagName.equals("男")) {
                                queryWrapper.or().like("gender", 0);
                        } else {
                                queryWrapper.like("tags", tagName);
                        }
                }
                List<User> userList = userMapper.selectList(queryWrapper);
                return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());
        }

        /**
         * todo 后面查询怎样实现
         */
        public Page<UserVO> searcherUserByTags1(List<String> tageNames, int size, int current) {
                if (CollectionUtils.isEmpty(tageNames)) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "标签不能为空");
                }
                Page<User> page = new Page<>(current, size);
                LambdaQueryChainWrapper<User> pj = new LambdaQueryChainWrapper<>(this.getBaseMapper());
                for (String s : tageNames) {
                        pj.like(User::getTags, s);
                }
                Page<User> userPage = userMapper.selectPage(page, pj);
                return getSafePageUser(userPage);
        }
}




